package cn.team11.smarteye.widget;

import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import cn.team11.sds.dayi.R;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.CalendarMode;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;

import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import cn.team11.smarteye.bean.AlarmMsgInfoBean;
import cn.team11.smarteye.bean.RingRecordBean;
import cn.team11.smarteye.module.MyDaoManager;
import cn.team11.smarteye.utils.TimeUtils;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Yang on 2017/11/4.
 */

public class GuestCalendarPopupView extends PopupWindow implements OnDateSelectedListener {
    private Activity mContextActivity;
    private View conentView;
    private MaterialCalendarView mCalendarView;
    private OnCalendarListener mListener;

    public GuestCalendarPopupView(Activity c){
        this.mContextActivity = c;
        initBasePopupWindow();
    }


    /**
     * 初始化BasePopupWindow的一些信息
     * */
    private void initBasePopupWindow() {
        LayoutInflater inflater = LayoutInflater.from(mContextActivity);
        conentView = inflater.inflate(R.layout.layout_calendar_popupwindow, null);

        //获取高度与宽度
        int h = mContextActivity.getWindowManager().getDefaultDisplay().getHeight();
        int w = mContextActivity.getWindowManager().getDefaultDisplay().getWidth();
        //
        setContentView(conentView);
        setWidth(w);
        setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

        setOutsideTouchable(true);  //默认设置outside点击无响应
        setFocusable(true);
        //刷新状态
        update();
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0000000000);
        // 点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ，设置其他控件变化等操作
        setBackgroundDrawable(dw);

        mCalendarView = (MaterialCalendarView) conentView.findViewById(R.id.calendarView);

        // 显示兴起补全的整个礼拜的上个月或者下个月的日期 一般会多出一行整个礼拜
        // 点击补全出来的另外一个月的信息 可以直接跳到那个月
        mCalendarView.setShowOtherDates(MaterialCalendarView.SHOW_ALL);
        // 设置日历默认的时间为当前的时间
        mCalendarView.setSelectedDate(new Date());
        mCalendarView.state().edit()
                // 设置你的日历 第一天是周一还是周一
                .setFirstDayOfWeek(Calendar.MONDAY)
                // 设置你的日历的最小的月份  月份为你设置的最小月份的下个月 比如 你设置最小为1月 其实你只能滑到2月
                .setMinimumDate(CalendarDay.from(2015, 1, 1))
                // 同最小 设置最大
                .setMaximumDate(new Date())
                // 设置你的日历的模式  是按月 还是按周
                .setCalendarDisplayMode(CalendarMode.MONTHS)
                .commit();
        mCalendarView.setBackgroundColor(ContextCompat.getColor(mContextActivity,R.color.color_main_bg));
        mCalendarView.setSelectionColor(ContextCompat.getColor(mContextActivity, R.color.color_main_green));
        mCalendarView.setOnDateChangedListener(this);

        final HashSet<CalendarDay> dates = new HashSet<>();
        Observable.create(new ObservableOnSubscribe<List<RingRecordBean>>() {
            @Override
            public void subscribe(@io.reactivex.annotations.NonNull ObservableEmitter<List<RingRecordBean>> e) throws Exception {

                e.onNext(MyDaoManager.getInstance(mContextActivity).getAllRings());

                e.onComplete();
            }
        }).flatMap(new Function<List<RingRecordBean>, Observable<RingRecordBean>>() {
            @Override
            public Observable<RingRecordBean> apply(@io.reactivex.annotations.NonNull List<RingRecordBean> alarmMsgInfoBeen) throws Exception {
                return Observable.fromIterable(alarmMsgInfoBeen);
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer<RingRecordBean>() {
            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

            }

            @Override
            public void onNext(@io.reactivex.annotations.NonNull RingRecordBean alarmMsgInfoBean) {
                String dateStr = TimeUtils.time2YMD(alarmMsgInfoBean.getRingtime());
                dates.add(new CalendarDay(TimeUtils.string2Date(dateStr)));
            }

            @Override
            public void onError(@io.reactivex.annotations.NonNull Throwable e) {

            }

            @Override
            public void onComplete() {
                mCalendarView.addDecorator(new EventDecorator(mContextActivity, dates));
            }
        });

    }

    @Override
    public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {
        String monthDay = TimeUtils.dateToString(date.getDate());
        if (mListener != null){
            mListener.onSelectedDateString(monthDay);
        }
        dismiss();
    }

    public interface OnCalendarListener {
        void onSelectedDateString(String dateStr);
    }

    public void setOnCalendarListener(OnCalendarListener listener) {
        this.mListener = listener;
    }

}
